package com.ruoyi.safe;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

//@Component
public class Licence implements HandlerInterceptor {

    @Getter
    private static Date endTime;

    @Autowired
    private ApplicationContext context;
    @Value("${licence}")
    private String licence;

    @PostConstruct
    public void init() {
        try {
            String decrypt = decrypt(licence);
            endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(decrypt);
            if(endTime.before(new Date())){
                throw new Exception();
            }else{
                System.out.println("许可证有效，有效期至："+endTime);
            }
        } catch (Exception e) {
            System.out.println("许可证过期，请联系管理员");
            SpringApplication.exit(context);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(endTime.before(new Date())){
            response.setStatus(422);
            response.getWriter().write(new AjaxResult(422,"许可证过期，请联系管理员").toString());
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private static String decrypt(String cipherText) throws Exception {
        // 将私钥字符串解码为字节数组
        byte[] keyBytes = Base64.getDecoder().decode("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCLR85JO0oZUFiv+DKxQFfaXl2Yrg84lz/2HTIrfmzD8X/MB9yvxq0XqwrJmiWwaj5aXiZOA4TpDiZoqis3tTEmsvaQf9XYXxu5WADcwp5qGZF0eQMGOtx9GKZEe+WuZ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2htso7s17rHedsuoSSxwKBgQCgWIszmTABadEMzHUYqho7i0PAXVnCRRBZ/zGzn+3aJxXyh6x4uUePGVKLSJceTqI4c88w42nnlnE4rTqnjfjnRFtRKLo0CBbsG7SnezkYzq3vWW1+jF010lGxyaad8exdPGafiBhRzYDZUFw4sXeTsWy4/vmmr2uNjJ+yar7J5QKBgAqO+JFD/YWbRJpPzV1PosZgUDmC9SUHOpzH0ggHk4ZORPDXCwzkyVGsN70j5c3m1sVW49H717ueOwhyVZF2WIq/S8BxFvb+J+aCkCzDaapXiwBfkXyRB9DmbYgqHDK8vQKIUZFxLFaDXQX29etPrLlksaPxr4MKEODxJIeGppd5");
        // 生成私钥对象（PKCS8EncodedKeySpec）
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // 获取Cipher实例，初始化为解密模式
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));

        return new String(decryptedBytes, "UTF-8");
    }
}
